<?php
declare (strict_types=1);

namespace app\index\middleware;

use think\facade\Cookie;
use think\Response;
use think\facade\Cache;
use app\common\model\User;
use app\common\controller\Config;
use think\exception\HttpResponseException;

class Verify
{
    public function handle($request, \Closure $next)
    {

        $system = Cache::get('system');
        if (!$system) {
            $system = Config::lists();
            Cache::set('system', $system);
        }
        if ($system['web_site_close'] != 1) {
            $this->friendlyError($request, $system['close_msg'], base_path() . 'error/close.html', 'view');
        }

//        if ($request->isPost()) {
//            $result = $this->verifyFrequent($request);
//            if (!$result) {
//                $this->friendlyError($request, '您的操作过于频繁，请稍后再试！');
//            }
//        }

        $result = $this->verifyToken();
        if ($result['code'] !== 1) {
            $this->friendlyError($request, $result['msg'], url('login/index')->build());
        }
        $request->user = $result['result'];
        $request->system = $system;

        return $next($request);

    }

    protected function verifyToken()
    {
        $token = Cookie::get('token');
        if (!$token) return ['code' => -1, 'msg' => '登录已过期'];
        $user = User::where('token', $token)->find();
        if (empty($user)) return ['code' => -1, 'msg' => '登录已过期'];
        if ($user->is_lock) return ['code' => -1, 'msg' => '账号已冻结'];

        return ['code' => 1, 'result' => $user];
    }

    protected function verifyFrequent($request)
    {
        $array = json_encode(['ip' => $request->ip(), 'action' => $request->action()]);
        if (Cache::get($array)) {
            return false;
        }
        Cache::set($array, 1, 1);

        return true;
    }

    public function friendlyError($request, $message, $url = '', $type = '')
    {
        if (!$request->isAjax()) {
            $response = Response::create($url, $type ? $type : 'redirect');
        } else {
            $result = [
                'code' => 0,
                'msg' => $message,
                'url' => $url,
            ];
            $response = Response::create($result, 'json');
        }
        throw new HttpResponseException($response);
    }
}